<?php

class Crud_Form_Element_Column_Digits extends Crud_Form_Element_Column
{	
	public function init()
	{
		$min = -2147483648;
		$max = 4294967295;
		
		$unsigned = $this->getColumn()->isUnsigned();
		$type = $this->getColumn()->getType();
		
		// Set min when unsigned
		if ($unsigned) {
			$min = 0;
			
			switch ($type) {
				case 'tinyint' :
					$max = 255;
					break;
				case 'smallint' :
					$max = 65535;
					break;
				case 'mediumint' :
					$max = 16777215;
					break;
				case 'int' :
					$max = 4294967295;
					break;
			}
		} else {
			switch ($type) {
				case 'tinyint' :
					$min = -128;
					$max = 127;
					break;
				case 'smallint' :
					$min = -32768;
					$max = 32767;
					break;
				case 'mediumint' :
					$min = -8388608;
					$max = 8388607;
					break;
				case 'int' :
					$min = -2147483648;
					$max = 2147483647;
					break;
			}
		}
		
		$element = $this->getElement();
		$element->addValidator(new Zend_Validate_Digits());
		
		if ($type == 'bigint') {
			return;
		}
		
		$element->addValidator(new Zend_Validate_LessThan($max + 1));
		$element->addValidator(new Zend_Validate_GreaterThan($min - 1));
		$size = strlen($max);
		$element->setAttrib('size', $size);
		$element->setAttrib('maxlength', $size);
	}
	
}
